"""VisitorSheet schemas for API validation and serialization."""

from __future__ import annotations

from datetime import date, time, datetime
from typing import Optional

from pydantic import BaseModel, Field, ConfigDict, field_validator

from ..models.enums import IntentionLevel


class VisitorSheetBase(BaseModel):
    """Base visitor sheet schema."""

    lead_id: int = Field(..., description="客户ID")
    property_id: int = Field(..., description="房源ID")
    agent_id: int = Field(..., description="经纪人ID")
    visit_date: date = Field(..., description="带看日期")

    visit_time: Optional[time] = Field(None, description="带看时间")
    duration_minutes: Optional[int] = Field(None, ge=0, le=1440, description="停留时长(分钟)")
    satisfaction: Optional[int] = Field(None, ge=1, le=5, description="满意度(1-5星)")
    pros_tags: Optional[str] = Field(None, max_length=500, description="优点标签(逗号分隔)")
    cons_tags: Optional[str] = Field(None, max_length=500, description="缺点标签(逗号分隔)")
    intention: IntentionLevel = Field(default=IntentionLevel.MEDIUM, description="意向度")
    notes: Optional[str] = Field(None, description="备注")

    @field_validator("satisfaction")
    @classmethod
    def validate_satisfaction(cls, v: Optional[int]) -> Optional[int]:
        """Validate satisfaction rating is between 1-5."""
        if v is not None and (v < 1 or v > 5):
            raise ValueError("满意度必须在1-5星之间")
        return v


class VisitorSheetCreate(VisitorSheetBase):
    """Schema for creating a new visitor sheet."""

    pass


class VisitorSheetQuickCreate(BaseModel):
    """Schema for quick-create visitor sheet (Phase 2: 快捷模式)."""

    lead_id: int = Field(..., description="客户ID")
    property_id: int = Field(..., description="房源ID")
    agent_id: int = Field(..., description="经纪人ID")
    visit_date: date = Field(..., description="带看日期")
    quick_notes: str = Field(..., min_length=10, max_length=2000, description="带看情况（快速输入）")

    # AI自动提取的可选字段（用户可在前端编辑后再提交）
    satisfaction: Optional[int] = Field(None, ge=1, le=5)
    intention: Optional[IntentionLevel] = None
    pros_tags: Optional[str] = None
    cons_tags: Optional[str] = None
    visit_time: Optional[time] = None
    duration_minutes: Optional[int] = Field(None, ge=0, le=1440)


class VisitorSheetUpdate(BaseModel):
    """Schema for updating visitor sheet."""

    visit_date: Optional[date] = None
    visit_time: Optional[time] = None
    duration_minutes: Optional[int] = Field(None, ge=0, le=1440)
    satisfaction: Optional[int] = Field(None, ge=1, le=5)
    pros_tags: Optional[str] = Field(None, max_length=500)
    cons_tags: Optional[str] = Field(None, max_length=500)
    intention: Optional[IntentionLevel] = None
    notes: Optional[str] = None

    @field_validator("satisfaction")
    @classmethod
    def validate_satisfaction(cls, v: Optional[int]) -> Optional[int]:
        """Validate satisfaction rating."""
        if v is not None and (v < 1 or v > 5):
            raise ValueError("满意度必须在1-5星之间")
        return v


class VisitorSheetOut(VisitorSheetBase):
    """Schema for visitor sheet output."""

    id: int
    created_at: datetime
    updated_at: datetime

    model_config = ConfigDict(from_attributes=True)


class VisitorSheetWithDetails(VisitorSheetOut):
    """Schema for visitor sheet with related entity details."""

    lead_name: Optional[str] = None
    lead_phone: Optional[str] = None
    property_address: Optional[str] = None
    agent_name: Optional[str] = None

    model_config = ConfigDict(from_attributes=True)


class VisitorSheetListOut(BaseModel):
    """Schema for paginated visitor sheet list."""

    total: int
    items: list[VisitorSheetOut]
    page: int
    page_size: int


class VisitorSheetImportItem(BaseModel):
    """Schema for Excel import visitor sheet item."""

    customer_name: str = Field(..., description="客户姓名")
    customer_phone: str = Field(..., description="客户电话")
    property_address: str = Field(..., description="房源地址")
    visit_date: date = Field(..., description="带看日期")
    agent_name: str = Field(..., description="经纪人姓名")

    duration_minutes: Optional[int] = None
    satisfaction: Optional[int] = Field(None, ge=1, le=5)
    pros_tags: Optional[str] = None
    cons_tags: Optional[str] = None
    intention: Optional[str] = None  # Will be converted to IntentionLevel
    notes: Optional[str] = None
